package com.sgd;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolDemo2 {

    private static int COREPOOLSIZE = 2;
    private static int MAXIMUMPOOLSIZE = 4;//最大线程数
    private static int KEEPALIVETIME = 60;

    public static void main(String[] args) {
        ThreadPoolDemo2 threadPoolDemo2 = new ThreadPoolDemo2();
        threadPoolDemo2.execute1();
    }

    public void execute1() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                COREPOOLSIZE,
                MAXIMUMPOOLSIZE,
                KEEPALIVETIME,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new _ThreadFactory()
        );

        // i 是 待处理的次数 或 内容
        for (int i = 0; i < 100; i++) {
            /**
             * Task （多线程）的实现：
             * 1.implements Runnable 接口
             * 2.Lambda 表达式
             */
            Task task = new Task(i);
            executor.execute(task);
        }

        // 关闭线程池
        executor.shutdown();

        // 等待线程池中的任务完成执行，最多等待60分钟
        try {
            boolean res = executor.awaitTermination(60, TimeUnit.MINUTES);
            if (res) {
                System.out.println("All tasks completed within the specified time.");
            } else {
                System.out.println("Some tasks are still running after the specified time.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 线程工厂：创建线程对象
 * <p>
 * 设置线程的属性：线程名称、优先级等
 * 为线程分配资源
 * 实现自定义线程管理逻辑
 */
class _ThreadFactory implements ThreadFactory {
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    public _ThreadFactory() {

    }
    @Override
    public Thread newThread(Runnable r) {
           /* Thread thread = new Thread(r);
            thread.setName("Thread-" + thread.getId());*/
        Thread thread = new Thread(r, "Thread-" + Thread.currentThread().getName()+threadNumber.getAndIncrement());
        return thread;
    }
}

/**
 * 待执行的任务
 */
class Task implements Runnable {
    /**
     * 如果要对某些变量执行多线程
     * 可以定义 private final 对象
     * 然后通过 构造方法 来获取外部参数
     */
    private int num;

    public Task(int i) {
        num = i;
    }

    // 多线程执行
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "执行了" + num);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "结束了" + num);
    }
}